let _vue = null;
export default class VueRouter {
    static install(Vue) {
        if (VueRouter.install.installed) {
            return
        }
        VueRouter.install.installed = true;
        _vue = Vue;
        _vue.mixin({
            beforeCreate() {
                if (this.$options.router) {
                    _vue.prototype.$router = this.$options.router;
                    this.$options.router.init();
                }
            }
        })
    }
    constructor(options) {
        this.$options = options;
        this.routerMap = {};
        this.data = _vue.observable({
            current: '/'
        })
    }
    init() {
        this.createRouteMap();
        this.initComponents(_vue);
        this.initEvent();
    }
    createRouteMap() {
        this.$options.routes.forEach(route => {
            this.routerMap[route.path] = route.component
        })
    }
    initComponents(Vue) {
        Vue.component('router-link', {
            props: {
                to: String
            },
            // template: '<a :href="to"><slot></slot></a>'
            render(h) {
                return h('a', {
                    attrs: {
                        href: this.to
                    },
                    on: {
                        click: this.clickHandler
                    }
                }, [this.$slots.default])
            },
            methods: {
                clickHandler(e) {
                    // history.pushState({}, {}, this.to)
                    // this.$router.data.current = this.to
                    this.$router.data.current = location.origin + '/#' + this.to;
                    location.href = location.origin + '/#' + this.to;
                    e.preventDefault();
                }
            }
        })
        const self = this;
        Vue.component('router-view', {
            render(h) {
                var str = self.data.current.replace(location.origin + '/#', '')
                const component = self.routerMap[str]
                // const component = self.routerMap[self.data.current]
                return h(component)
            }
        })
    }
    initEvent() {
        window.addEventListener('hashchange', () => {
            this.data.current = window.location.hash.slice(1)
            // this.data.current = window.location.pathname
        })
        // window.addEventListener('popstate', () => {
        //     this.data.current = window.location.pathname
        // })
    }
}